package com.webshop.DataDao;

import com.webshop.JavaBean.Address;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class AddressDao {
    QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());

    /**
     * 获取用户指定的地址
     * @param ID
     * @return
     */
    public Address getChoiceAddress(String ID) {
        String sql = "select * from address where ID = ?";
        Address address = null;
        try {
            address = qr.query(sql, new BeanHandler<>(Address.class), ID);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return address;
    }

    /**
     * 用户插入地址信息。
     * @param address
     */
    public void insertAddress(Address address) throws Exception {
        String sql = "insert into address (user,address,phone,addressee) values(?,?,?,?)";
        Object[] parm = {address.getUser(),address.getAddress(),address.getPhone(),address.getAddressee()};
        qr.update(sql, parm);

    }

    /**
     * 用户修改地址信息
     * @param address
     */
    public void modifyInfo(Address address) throws Exception {
        //根据用户使用的 地址ID 进行修改。
        String sql="update address set " +
                   "address = ? ," +
                   "phone = ? ," +
                "addressee = ? " +
                "WHERE ID =? ";
        Object[] parm = {address.getAddress(),address.getPhone(),address.getAddressee(),address.getID()};
        qr.update(sql, parm);

    }

    /**
     * 删除用户指定的信息。
     * @param ID
     */
    public void deleteInfo(String ID) throws Exception
    {
        String sql = "delete from address where ID = ? ";
        qr.update(sql, ID);

    }

    /**
     * 返回该用户的所有地址信息。
     * @param name
     * @return
     */
    public List<Address> addressInfo(String name) {
        String sql = "select *  from address where user = ? ";
        List<Address> userAddress = new ArrayList<>();
        try {
            userAddress = qr.query(sql, new BeanListHandler<>(Address.class), name);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //如果userAddress 为空，可能会有为空的错误。不一定会有
        return userAddress;
    }
}
